package gold.enterprise;

import gold.utils.InputUtil;


public class Haoweilai {

    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int x) {
            val = x;
        }

        public ListNode createList(String list) {
            String[] nodeList = list.split("->");
            ListNode start = new ListNode(Integer.parseInt(nodeList[0].trim()));
            ListNode curNode = start;
            for (int i = 1; i < nodeList.length; i++) {
                curNode.next = new ListNode(Integer.parseInt(nodeList[i].trim()));
                curNode = curNode.next;
            }

            return start;
        }

        public static ListNode createListFromArrayString(String input) {
            int[] valArray = InputUtil.toIntegerArray(input);
            ListNode start = new ListNode(valArray[0]);
            ListNode curNode = start;
            for (int i = 1; i < valArray.length; i++) {
                curNode.next = new ListNode(valArray[i]);
                curNode = curNode.next;
            }

            return start;
        }
    }


    public boolean isExistCycle(ListNode head) {
        if (null == head || null == head.next) return false;

        ListNode fast = head.next, slow = head;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;  //末尾还未相遇，无还
            }

            slow = slow.next;         //步进一
            fast = fast.next.next;    //步进二
        }

        //相遇则有环
        return true;
    }

    public ListNode getCycleEntry(ListNode head) {
        return null;
    }


    public void run() {
        ListNode head = ListNode.createListFromArrayString("1");
        ListNode cycleEntryNode = new ListNode(6);
        ListNode cycleEntryNextNode = new ListNode(7);
        head.next = cycleEntryNode;
        cycleEntryNode.next = cycleEntryNextNode;
        cycleEntryNextNode.next = cycleEntryNode;
        System.out.println(this.isExistCycle(head));


    }


    public static void main(String[] args) {
        Haoweilai runner = new Haoweilai();
        runner.run();
    }

}
